/**
 * 
 * Copyright (C) 2015 by Elcom Software Company
 *
 * @id: DbConnectionPool.java, Feb 5, 2015
 *
 */
package com.nip.commons.dbcp;

import java.sql.Connection;

import org.apache.commons.dbcp2.BasicDataSource;

import com.nip.commons.dbcp.interf.IDBConfig;
import com.nip.commons.dbcp.interf.IDBPool;

/**
 * @author ThangNM<thangnm@elcom.com.vn>
 *
 * @version v
 */
public class DbConnectionPool implements IDBPool {

    private final BasicDataSource datasource;
    
    
    
    public DbConnectionPool(IDBConfig dbcfg) throws Exception {
        super();
        this.datasource = new BasicDataSource();
        init(dbcfg);
    }

    /* (non-Javadoc)
     * @see com.nip.commons.dbcp.interf.IDBPool#getConnection()
     */
    @Override
    public Connection getConnection() throws Exception {
        return datasource.getConnection();
    }

    /* (non-Javadoc)
     * @see com.nip.commons.dbcp.interf.IDBPool#init(com.nip.commons.dbcp.interf.IDBConfig)
     */
    @Override
    public void init(IDBConfig dbcfg) throws Exception {
        this.datasource.setDefaultAutoCommit(dbcfg.getAutoCommit());
        this.datasource.setCacheState(dbcfg.getCacheState());
        this.datasource.setDriverClassName(dbcfg.getDriver());
        this.datasource.setUrl(dbcfg.getUrl());
        this.datasource.setUsername(dbcfg.getUsername());
        this.datasource.setPassword(dbcfg.getPassWord());
        this.datasource.setInitialSize(dbcfg.getInitialSize());
        this.datasource.setMaxTotal(dbcfg.getMaxTotal());
        this.datasource.setMaxIdle(dbcfg.getMaxIdle());
        this.datasource.setMinIdle(dbcfg.getMinIdle());
        this.datasource.setMaxWaitMillis(dbcfg.getMaxWaitMillis());
        this.datasource.setMaxConnLifetimeMillis(dbcfg.getMaxConnLifetimeMillis());
        if(dbcfg.getValidationQuery() != "")
        {
            this.datasource.setValidationQuery(dbcfg.getValidationQuery());
        }
    }

}
